/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

import React, { Component } from 'react';
import {
    AppRegistry, Platform, Alert, NetInfo
} from 'react-native';
import Navigation from './js/config/Entry';
import {
    isFirstTime,
    isRolledBack,
    packageVersion,
    currentVersion,
    checkUpdate,
    downloadUpdate,
    switchVersion,
    switchVersionLater,
    markSuccess,
} from 'react-native-update';

import _updateConfig from './update.json';
const {appKey} = _updateConfig[Platform.OS];

export default class Tikuanji extends Component {

    componentWillMount() {
        if (isFirstTime) {
            markSuccess();
        } else if (isRolledBack) {
        }
        this.checkUpdate();
    }
    doUpdate = info => {
        downloadUpdate(info).then(hash => {
            Alert.alert('提示', '下载完毕,是否重启应用?', [
                { text: '是', onPress: () => { switchVersion(hash); } },
                { text: '否', },
                { text: '下次启动时', onPress: () => { switchVersionLater(hash); } },
            ]);
        }).catch(err => {
            Alert.alert('提示', '更新失败.');
        });
    };
    checkUpdate = () => {
        checkUpdate(appKey).then(info => {
            if (info.expired) {
                Alert.alert('提示', '您的应用版本已更新,请前往应用商店下载新的版本', [
                    { text: '确定', onPress: () => { info.downloadUrl && Linking.openURL(info.downloadUrl) } },
                ]);
            } else if (info.upToDate) {
                console.log(info.metaInfo)
            } else {
                Alert.alert('提示', '检查到新的版本' + info.name + ',是否下载?\n' + info.description, [
                    { text: '是', onPress: () => { this.doUpdate(info) } },
                    { text: '否', },
                ]);
            }
        }).catch(err => {
            Alert.alert('提示', '更新失败.');
        });
    };

    // 下面是info的数据结构

    //  { update: true, hash: 'FkqYlmcO3Ijsk226OQiG578zelbp',

    //   name: '(未命名)',

    //   description: '',

    //   metaInfo: '{\'bug\':111}',

    //   updateUrl: 'http://update-packages.reactnative.cn/FkqYlmcO3Ijsk226OQiG578zelbp?e=1488126232&token=made75kGFhOozkiRfa7LK_E1xG1pLOnhW8fhbnev:HcZ78myMdBtTV_dp87bT-OrEGoU=',

    //   pdiffUrl: 'http://update-packages.reactnative.cn/lmueAn2cSkXifBXud3HyCDXfd8N6-FkqYlmcO3Ijsk226OQiG578zelbp.pdiff?e=1488126232&token=made75kGFhOozkiRfa7LK_E1xG1pLOnhW8fhbnev:p0WwpnmX8mL963qr_lg7RN5rCNQ=',

    //   diffUrl: 'http://update-packages.reactnative.cn/FvjO2LZ6PBokZH7tEXVEQJp5FbTr-FkqYlmcO3Ijsk226OQiG578zelbp.diff?e=1488126232&token=made75kGFhOozkiRfa7LK_E1xG1pLOnhW8fhbnev:mu6doE2SjevrlIsxlAHLCSyjO_o=',

    //   ok: 1 }

    render() {
        return (
            <Navigation />
        );
    }
}


AppRegistry.registerComponent('Tikuanji', () => Tikuanji);
